package org.nightrunner.d3.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.nightrunner.d3.entity.Property;
import org.springframework.stereotype.Service;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Service
public class JsonService {

	/*
	 * public JsonObject getObject(Question question) { JsonObject object = new
	 * JsonObject(); object.addProperty("questionName",
	 * question.getQuestionName()); object.addProperty("questionId",
	 * question.getQuestionId()); return object; }
	 * 
	 * public JsonObject getObject(Key key) { JsonObject object = new
	 * JsonObject(); object.addProperty("keyName", key.getKeyName());
	 * object.addProperty("keyId", key.getKeyId()); return object; }
	 * 
	 * public JsonArray getObjects(List<Key> keys) { JsonArray jsonArray = new
	 * JsonArray();
	 * 
	 * for (Key key : keys) { jsonArray.add(getObject(key)); }
	 * 
	 * return jsonArray; }
	 */
	public JsonObject getObject(Object object) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		JsonObject returnObject = new JsonObject();

		Method[] methods = object.getClass().getMethods();
		for (Method method : methods) {
			if (method.getName().startsWith("get")
					&& !"getClass".equals(method.getName())) {
				returnObject.addProperty(firstToLower(method.getName()
						.substring(3)), (String) method.invoke(object));
			}
		}

		return returnObject;
	}

	private String firstToLower(String str) {
		return str.substring(0, 1).toLowerCase() + str.substring(1);
	}

	public static void main(String[] args) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		JsonService util = new JsonService();
		System.out.println(util.getObject(new Property()));
	}

	public JsonArray getObjects(List<? extends Object> objects)
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		JsonArray jsonArray = new JsonArray();
		for (Object object : objects) {
			jsonArray.add(getObject(object));
		}
		return jsonArray;
	}
}